#include <sstream>
#include "CPolygon.h"
#include "TypeDefinitions.h"
#include <iostream>

CPolygon::CPolygon(Verticles* v, ColorT* c, OpacityT o) :
	verticles(v),
	color(c),
	opacity(o)
{
	calculateBox();
}

CPolygon* CPolygon::copy()
{
	Verticles* _verticles = new Verticles(verticles->width(), 2, 1, 1, 0);
	for(int i = 0; i<verticles->width(); i++)
	{
		(*_verticles)(i, 0) = (*verticles)(i, 0);
		(*_verticles)(i, 1) = (*verticles)(i, 1);
	}

	ColorT* _color = new ColorT[channelsNumber];
	for(int i = 0; i<channelsNumber; i++)
	{
		(_color)[i]=(color)[i];
	}

	CPolygon* triangle = new CPolygon(_verticles, _color, opacity);
	triangle->leftUpX = leftUpX;
	triangle->leftUpY = leftUpY;
	triangle->rightBottomX = rightBottomX;
	triangle->rightBottomY = rightBottomY;

	triangle->neighbours = neighbours;
	triangle->positionZ = positionZ;

	return triangle;
}

CPolygon::~CPolygon(void) 
{
	delete verticles;
	delete[] color;
}

void CPolygon::calculateBox()      //sprawdzic czy musi byc zawsze wyliczane w momencie tworzenia polygonu i zmieniania wierzcholkow. Moze wystarczy tylko na zadanie w mutatorze.
{
	leftUpX = (*verticles)(0, 0);
	leftUpY = (*verticles)(0, 1);
	rightBottomX = (*verticles)(0, 0);
	rightBottomY = (*verticles)(0, 1);

	for(int i=0; i<verticles->width(); i++)
	{
		leftUpX = std::min(leftUpX, (*verticles)(i, 0));
		leftUpY = std::min(leftUpY, (*verticles)(i, 1));

		rightBottomX = std::max(rightBottomX, (*verticles)(i, 0));
		rightBottomY = std::max(rightBottomY, (*verticles)(i, 1));
	}
}


std::string CPolygon::toSVG()
{
	std::stringstream stream;

	stream<<"<polygon points=\"";
			
	for(int i = 0; i<verticles->width() - 1; i++)
	{
		stream<<(*verticles)(i,0)<<","<<(*verticles)(i,1)<<", ";
	}
		
	stream<<(*verticles)(verticles->width() - 1,0)<<","<<(*verticles)(verticles->width() - 1,1);
			
	stream<<"\" style=\"fill:rgba("<<(int)color[0]<<","<<(int)color[1]<<","<<(int)color[2]<<","<<opacity<<");stroke:none\"/>"<<std::endl;
	return stream.str();
}


void CPolygon::print()
{
	 std::cout<<"[";
	for(int i=0; i < verticles->width(); i++)
	{
		 std::cout<<(int)(*verticles)(i, 0)<<", "<<(int)(*verticles)(i, 1)<<"    ";
	}
	 std::cout<<"] c="<<(int)color[0]<<";"<<(int)color[1]<<";"<<(int)color[2]<<" o="<<(float)opacity<<std::endl;
}